const fs = require("fs");
const path = require("path");

//将base64转换为blob
module.exports.dataURLtoBlob = (dataurl) => {
  const arr = dataurl.split(",");
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(arr[1]);
  const n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
};
//将blob转换为file
module.exports.blobToFile = (theBlob, fileName) => {
  theBlob.lastModifiedDate = new Date();
  theBlob.name = fileName;
  return theBlob;
};

// base64转文件
module.exports.base64ToFile = (imgData, path) => {
  const base64Data = imgData.replace(/^data:image\/\w+;base64,/, "");
  const dataBuffer = new Buffer(base64Data, "base64");
  fs.writeFileSync(
    path,
    dataBuffer,
    (err) => {
      if (err) {
        return false;
      } else {
        return true;
      }
    }
  );
  return true
};

// 删除文件
module.exports.delFile = (dirPath, fileName) => {
  fs.unlink(path.join(dirPath, fileName), (err) => {
    if (err) {
      console.log('删除失败');
    } else {
      console.log('删除成功');
    }
  });
  return true
}